package com.stylefeng.guns.rest.modular.user;

import java.io.File;
import java.util.UUID;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.stylefeng.guns.core.base.tips.ErrorTip;
import com.stylefeng.guns.core.base.tips.SuccessTip;
import com.stylefeng.guns.rest.common.persistence.dao.UserMapper;
import com.stylefeng.guns.rest.common.persistence.model.User;
import com.stylefeng.guns.rest.config.properties.GunsProperties;
import com.stylefeng.guns.rest.modular.file.FileController;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

/**
 * 常规控制器
 *
 * @author fengshuonan
 * @date 2017-08-23 16:02
 */
@RestController
@RequestMapping("/user")
public class UserController {
	
	private static Logger log = LoggerFactory.getLogger(UserController.class);
	
    @Resource
    private GunsProperties gunsProperties;
	
	 @Autowired
	 private UserMapper userMapper;
	
	//文档生成参照：http://blog.csdn.net/saytime/article/details/74937664

	
	// http://127.0.0.1:8081/user/register
	@ApiOperation(value="用户注册", notes="用户注册")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "account", value = "用户账号", required = true,dataType = "String",paramType="query"),
		@ApiImplicitParam(name = "password", value = "密码", required = true,dataType = "String",paramType="query")
	})
    @ApiResponses({
       @ApiResponse(code=200,message="操作成功!"),
       @ApiResponse(code=201,message="账号已存在!")
    })
	@PostMapping("register")
	public ResponseEntity<?> register(User user) {
		User userB = new User();
		userB.setAccount(user.getAccount());
		userB = this.userMapper.selectOne(userB);
		if(userB != null){
			return new ResponseEntity<>(new ErrorTip(201,"账号已存在!"),HttpStatus.OK);
		}
		userMapper.insert(user);
		return new ResponseEntity<>(new SuccessTip(user.getId()),HttpStatus.OK);
		//return ResponseEntity.ok(list);
	}
    
    
	// http://127.0.0.1:8081/user/login
	@ApiOperation(value="用户登陆", notes="用户登陆")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "account", value = "用户账号", required = true,dataType = "String",paramType="query"),
		@ApiImplicitParam(name = "password", value = "密码", required = true,dataType = "String",paramType="query")
	})
    @ApiResponses({
       @ApiResponse(code=200,message="操作成功!"),
       @ApiResponse(code=201,message="操作失败!")
    })
	@PostMapping("login")
	public ResponseEntity<?> login(User user) {
		User userB = new User();
		userB.setAccount(user.getAccount());
		userB.setAccount(user.getPassword());
		userB = this.userMapper.selectOne(userB);
		if(userB != null){
			return new ResponseEntity<>(new SuccessTip(userB),HttpStatus.OK);
		}
		return new ResponseEntity<>(new ErrorTip(201,"操作失败!"),HttpStatus.OK);
		//return ResponseEntity.ok(list);
	}
    
    
	// http://127.0.0.1:8081/user/querById
	@ApiOperation(value="查询用户详情", notes="根据用户编号查询用户详情")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "id", value = "用户编号", required = true,dataType = "int",paramType="query")
	})
    @ApiResponses({
       @ApiResponse(code=200,message="操作成功!"),
       @ApiResponse(code=201,message="操作失败!")
    })
	@PostMapping("querById")
	public ResponseEntity<?> querById(User user) {
		User userB = new User();
		userB = this.userMapper.selectById(user.getId());
		if(userB != null){
			return new ResponseEntity<>(new SuccessTip(userB),HttpStatus.OK);
		}
		return new ResponseEntity<>(new ErrorTip(201,"操作失败!"),HttpStatus.OK);
		//return ResponseEntity.ok(list);
	}
    
	// http://127.0.0.1:8081/user/save
	@ApiOperation(value="完善个人信息", notes="完善个人信息")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "id", value = "用户编号", required = true,dataType = "Long",paramType = "query"),
		@ApiImplicitParam(name = "name", value = "名字", required = true,dataType = "String",paramType = "query"),
		@ApiImplicitParam(name = "birthday", value = "生日", required = true,dataType = "Date",paramType = "query"),
		@ApiImplicitParam(name = "sex", value = "性别（1：男 2：女）", required = true,dataType = "int",paramType = "query"),
		@ApiImplicitParam(name = "email", value = "电子邮件", required = true,dataType = "String",paramType = "query"),
		@ApiImplicitParam(name = "phone", value = "电话", required = true,dataType = "String",paramType = "query"),
		@ApiImplicitParam(name = "avatar", value = "头像", required = true,dataType = "String",paramType = "query")
	})
	@PostMapping("save")
    public ResponseEntity<?> save(User user) {
		userMapper.insert(user);
        return new ResponseEntity<>(new SuccessTip(),HttpStatus.OK);
        //return ResponseEntity.ok(list);
    }
	
	
	
    /**
     * 上传图片(上传到项目的webapp/static/img)
     */
    @PostMapping("upload")
    public ResponseEntity<?> upload(@RequestPart("file") MultipartFile picture) {
        String pictureName = UUID.randomUUID().toString() + ".jpg";
        try {
            String fileSavePath = gunsProperties.getFileUploadPath();
            picture.transferTo(new File(fileSavePath + pictureName));
        } catch (Exception e) {
        	e.printStackTrace();
            return new ResponseEntity<>(new ErrorTip(201,"操作失败!"),HttpStatus.OK);
        }
        return new ResponseEntity<>(new SuccessTip(),HttpStatus.OK);
    }
	
	//========多文件上传=========================================
    /***
	 * 保存文件
	 * @param file
	 * @return
	 */
	private boolean saveFile(MultipartFile file) {
		//String pictureName = UUID.randomUUID().toString() + ".jpg";
		String fileName = file.getOriginalFilename();
		String suffix = fileName.substring(fileName.lastIndexOf(".")+1);
		String pictureName = UUID.randomUUID().toString() + suffix;
		// 判断文件是否为空
		if (!file.isEmpty()) {
			try {
				// 文件保存路径
				//String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"+ file.getOriginalFilename();
				// 转存文件
				//file.transferTo(new File(filePath));
				
	            String fileSavePath = gunsProperties.getFileUploadPath();
	            file.transferTo(new File(fileSavePath + pictureName));
	            
	            //*****数据库操作*****************
	            
				return true;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return false;
	}
    
    
	@PostMapping("filesUpload")  
    public ResponseEntity<?> filesUpload(@RequestParam("files") MultipartFile[] files) {  
        //判断file数组不能为空并且长度大于0  
        if(files!=null&&files.length>0){  
            //循环获取file数组中得文件  
            for(int i = 0;i<files.length;i++){  
                MultipartFile file = files[i];  
                //保存文件  
                saveFile(file);  
            }  
        }  
        return new ResponseEntity<>(new SuccessTip(),HttpStatus.OK);
    }  
    
    //========多文件上传=========================================
    
    
    
    
    
    
	
	
	
    //==
}
